package com.cloudfast.common.user;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

import com.google.gson.Gson;

public class UserUtils {
    private static final Logger logger = LoggerFactory.getLogger(Logger.class);

    private static JSONObject principal() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        JSONObject obj = new JSONObject(authentication);
        return obj.getJSONObject("userAuthentication").getJSONObject("details").getJSONObject("principal");
    }

    /**
     * 获取当前的用户
     *
     * @return
     */
    public static LoginUser getUser() {
        try {
            JSONObject cache = principal().getJSONObject("cache");
            JSONObject user = cache.getJSONObject("user");
            Gson gson = new Gson();
            return gson.fromJson(user.toString(), LoginUser.class);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return null;
        }
    }

    /**
     * 获取用户拥有的菜单
     *
     * @return
     */
    public static List<Map<String, Object>> getUserMenus(String scope) {
        try {
            JSONObject cache = principal().getJSONObject("cache");
            String menuKey = scope.toLowerCase() + "_menus";
            if (cache.has(menuKey)) {
                JSONArray menus = cache.getJSONArray(menuKey);
                Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
                Type lisType = new TypeToken<LinkedList<Map<String, Object>>>() {
                }.getType();
                return gson.fromJson(menus.toString(), lisType);
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return null;

    }

    /**
     * 获取用户拥有的大屏入口
     *
     * @return
     */
    public static List<Map<String, Object>> getUserScreenButtons() {
        try {
            JSONObject cache = principal().getJSONObject("cache");
            JSONArray screenBtn = cache.getJSONArray("screenBtn");
            Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
            Type lisType = new TypeToken<LinkedList<Map<String, Object>>>() {
            }.getType();
            return gson.fromJson(screenBtn.toString(), lisType);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return null;
        }
    }

    /**
     * 当前用户拥有的权限字符串
     *
     * @return
     */
    public static List<String> getPermission() {
        List<String> permissionList = new ArrayList<String>();
        JSONArray authoritiesJSON = principal().getJSONArray("authorities");
        for (int i = 0; i < authoritiesJSON.length(); i++) {
            permissionList.add(authoritiesJSON.getJSONObject(i).getString("authority"));
        }
        return permissionList;
    }

    /**
     * 判的当前用户是否有权限
     *
     * @param permission 权限标识
     * @return
     */
    public static boolean hasPermission(String permission) {
        List<GrantedAuthority> authoritiesArrayTemp = new ArrayList<GrantedAuthority>();
        JSONArray authoritiesJSON = principal().getJSONArray("authorities");
        for (int i = 0; i < authoritiesJSON.length(); i++) {
            GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(
                    authoritiesJSON.getJSONObject(i).getString("authority"));
            authoritiesArrayTemp.add(grantedAuthority);
        }
        return authoritiesArrayTemp.contains(new SimpleGrantedAuthority(permission));
    }
}
